var mongoose = require('mongoose');
Schema = mongoose.Schema;

mongoose.connect('mongodb://127.0.0.1/test1');

var PersonSchema = new Schema({
	name : String,
	age : Number,
	stories : [ {
		type : Schema.ObjectId,
		ref : 'Story'
	} ]
});

var StorySchema = new Schema({
	_creator : {
		type : Schema.ObjectId,
		ref : 'Person'
	},
	title : String,
	fans : [ {
		type : Schema.ObjectId,
		ref : 'Person'
	} ]
});

var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);

// var aaron = new Person({
// name : 'Aaron',
// age : 100
// });
// aaron.save(function(err) {
//
// var story1 = new Story({
// title : "A man who cooked Nintendo",
// _creator : aaron._id
// });
//
// story1.save(function(err) {
// });
// });
//
// Story.findOne({
// title : /Nintendo/i
// }).populate('_creator').run(function(err, story) {
// console.log('The creator is ' + story._creator.name);
// });

// Story
// .findOne({ title: /Nintendo/i })
// .populate('_creator', ['name']) // <-- only return the Persons name
// .run(function (err, story) {
//	
// console.log('The creator is %s', story._creator.name);
// // prints "The creator is Aaron"
//
// console.log('The creators age is %s', story._creator.age);
// // prints "The creators age is null'
// });

//var guille = new Person({
//	name : 'Guillermo'
//});

//guille.save(function(err) {
//
//	console.log(guille.name);

	Story.findOne({
		title : /Nintendo/i
	}, function(story) {
		story._creator = guille; // or guille._id

		story.save(function(err) {
				if(err) 
			Story.findOne({
				title : /Nintendo/i
			}).populate('_creator', [ 'name' ]).run(function(err, story) {

				console.log('The creator is ' + story._creator.name);
				// prints "The creator is Guillermo"
			});
		});
	});
//});
